# -*-coding:utf-8 -*-
import os
import sys

# 配置Python WEB Flask识别项目自定义模块
from flask_login import login_user, LoginManager, current_user
from werkzeug import Response
from werkzeug.security import check_password_hash, generate_password_hash

from Database.init import get_flask_db
from WEB.app.models import AdminUser, User, AdminImportEmail
from WEB.app.router import admin as admin_router, Frontend

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
from flask import Flask, render_template, redirect, request, session, url_for

app = Flask(__name__)  # 创建一个wsgi应用
app.secret_key = os.urandom(24)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

db = get_flask_db(app)


@login_manager.user_loader
def load_user(user_id):
    """
    flask-login的用户加载函数
    :param user_id:
    :return:
    """
    session_keys = session.keys()
    have_not_user = True
    # if 'admin_user_id' in session_keys:
    if session.get('admin_user_id'):
        admin_user_id = session['admin_user_id']
        if admin_user_id:
            admin_user = AdminUser.query.filter(AdminUser.id == user_id).first()
            admin_user.area = 0
            return admin_user
    # if have_not_user is True and 'user_id' in session_keys:
    if have_not_user is True and session.get('user_id'):
        frontend_user_id = session['user_id']
        if frontend_user_id:
            user = User.query.filter(User.id == frontend_user_id).first()
            user.area = 1
            return user
        else:
            user = User.query.filter(User.id == user_id).first()
            user.area = 1
            return user
    return None


# --------------前台控制器--------------------------
@app.route('/', methods=['GET'])
def index():
    frontend = Frontend.User()
    return frontend.index()


@app.route('/register', methods=['GET', 'POST'])
def register():
    frontend = Frontend.User()
    return frontend.register(db)


@app.route('/login', methods=['GET', 'POST'])
def login():
    frontend = Frontend.User()
    return frontend.login()


@app.route('/logout', methods=['GET'])
def logout():
    frontend = Frontend.User()
    return frontend.logout()


@app.route('/excel/export', methods=['GET'])
def excel():
    return render_template('file/export-form.html')


@app.route('/admin/download', methods=['POST'])
def download():
    from WEB.app.router.file import download
    return download.download()


@app.route('/my/email/smtp', methods=['GET', "POST"])
def smtp():
    frontend = Frontend.Email()
    res = frontend.smtp(db=db)
    if isinstance(res, Response):
        return res
    return res


@app.route('/my/email/template', methods=['GET', "POST"])
def template():
    frontend = Frontend.Email()
    res = frontend.email_template(db=db)
    if isinstance(res, Response):
        return res
    return res


@app.route('/my/email/send', methods=['GET'])
def email():
    frontend = Frontend.Email()
    res = frontend.send(db=db)
    if isinstance(res, Response):
        return res
    return res


# --------------后台控制器--------------------------
@app.route('/admin')
def admin():
    return admin_router.index()


@app.route('/admin/login', methods=['GET', 'POST'])
def admin_login():
    from WEB.app.forms.AdminUser import get_admin_login_form
    form = get_admin_login_form()
    if request.method == 'GET':
        return render_template('admin/user/login.html', form=form)
    if request.method == 'POST':
        email = request.form.get('email')
        password = request.form.get('password')
        admin_user = AdminUser.query.filter(AdminUser.email == email).first()
        if admin_user:
            # 校验密码
            if check_password_hash(admin_user.password, password):
                # 使用flask_login 实现登陆后的操作
                login_user(admin_user)
                session['admin_user_id'] = admin_user.get_id()
                session['is_admin'] = True
                return redirect('/admin')
            else:
                return render_template('admin/user/login.html', msg='登录密码错误！', form=form)
        else:
            return render_template('admin/user/login.html', msg='账号不存在！', form=form)
    return render_template('admin/user/login.html', msg='', form=form)


@app.route('/admin/upload', methods=['GET', 'POST'])
def admin_upload():
    """
    上传文件：需要验证登录，未登录需要跳转登录
    :return:
    """
    from WEB.app.router.file import upload
    app.config['UPLOAD_FOLDER'] = upload.UPLOAD_FOLDER
    res = upload.admin_upload_file()
    if isinstance(res, Response):
        return res
    # class Res():
    #     pass
    # res = Res()
    # res.file_path = "E:\\WorkerSpace\\CP516\\InternetCelebrityDiscoverSpider\\WEB\\app\\upload\\admin\\202142\\56fe6b44-946d-4058-9d62-5c7be37e75f8.txt"
    admin_user_id = session.get('admin_user_id')
    lines = 0
    if admin_user_id is not None and res.is_success is True:
        print('准备处理数据...')
        file = open(res.file_path, 'r', encoding='utf-8')
        for line in file:
            admin_import_email = AdminImportEmail()
            try:
                email = line.split(':')[0]
                print(email)
                admin_import_email.importer_user_id = 1
                admin_import_email.email = email
                db.session.add(admin_import_email)
                db.session.commit()
                lines += 1
            except Exception as e:
                db.session.rollback()
                if str(e).find('1062'):
                    print('重复邮件：' + line)
    return render_template('admin/common/tool/msg.html', msg='一共导入：' + str(lines) + '个邮件', url=url_for('admin'))


@app.route('/admin/distribute_email', methods=['GET'])
def admin_distribute_email():
    return admin_router.admin_distribute_email()


@app.route('/admin/logout', methods=['GET'])
def admin_logout():
    return admin_router.logout()


# 处理数据
if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=516)  # 启动app的调试模式
